package com.gupao.rpc.protocol.server;

import com.gupao.rpc.protocol.constants.ReqType;
import com.gupao.rpc.protocol.protocol.Header;
import com.gupao.rpc.protocol.protocol.RpcProtocol;
import com.gupao.rpc.protocol.protocol.RpcRequest;
import com.gupao.rpc.protocol.protocol.RpcResponse;
import com.gupao.rpc.protocol.spring.SpringBeanManager;
import com.gupao.rpc.protocol.spring.service.Meditor;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author SuperWein
 */
@Slf4j
public class ServerChannelHandler extends SimpleChannelInboundHandler<RpcProtocol<RpcRequest>> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcProtocol<RpcRequest> requestRpcProtocol) throws Exception {
        log.info(requestRpcProtocol.toString());
        RpcProtocol<RpcResponse> rpcProtocol = new RpcProtocol<RpcResponse>();
        RpcResponse rpcResponse = new RpcResponse();
        Header header = requestRpcProtocol.getHeader();
        header.setReqType(ReqType.RESPONSE.value());
        rpcProtocol.setHeader(header);
        Object obj = Meditor.process(requestRpcProtocol.getBody());
        rpcResponse.setData(obj);
        rpcResponse.setMsg("success");
        rpcProtocol.setBody(rpcResponse);
        channelHandlerContext.writeAndFlush(rpcProtocol);
    }

    @Deprecated
    private Object methodInvoke(RpcRequest body) {
        try {
            Class<?> clazz = Class.forName(body.getClassName());
            Object bean = SpringBeanManager.getBean(clazz);
            Method method = clazz.getDeclaredMethod(body.getMethodName(), body.getParameterTypes());
            return method.invoke(bean, body.getParameters());
        } catch (ClassNotFoundException | NoSuchMethodException
                | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
